/**
 * 测试fork产生三个子进程，并使用主进程进行回收；
 * @author: sundx
 * @date: 2020-05-30 21:59:37
 * @Last Modified by: sundx
 * @Last Modified time: 2020-05-30 22:00:10
 */
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
int main() {
  int i;
  for (i = 0; i < 3; ++i) {
    if (fork() == 0) {
      break;
    }
  }
  switch (i) {
  case 0:
    std::cout << getpid() << " ps" << std::endl;
    execlp("ps", "ps", "aux", NULL);
    std::cout << "ps error" << std::endl;
    break;
  case 1:
    std::cout << getpid() << " ./hello" << std::endl;
    execl("./hello", "./hello", NULL);
    std::cout << "hello error" << std::endl;
    break;
  case 2:
    std::cout << getpid() << " ./testSegErr" << std::endl;
    execl("./testSegErr", "./testSegErr", NULL);
    std::cout << "testSegErr error" << std::endl;
    break;
  case 3:
    int status;
    pid_t wpid;
    while ((wpid = waitpid(-1, &status, WNOHANG)) != -1) {
      if (wpid > 0) {
        if (WIFSIGNALED(status)) {
          std::cout << wpid << "   " << WTERMSIG(status) << std::endl;
        }
        if (WIFEXITED(status)) {
          std::cout << wpid << "   " << WEXITSTATUS(status) << std::endl;
        }
      }
    }
  default:
    break;
  }
  return 0;
}